<template>
  <div class="page3">
    <Header :isGoBack="false">
      <template v-slot:right>
        <div class="btn" @click="goStudyCenter">返回</div>
      </template>
    </Header>
    <!-- <Head-comp></Head-comp> -->
    <div class="ctx">
      <div class="ctx-head">
        <div class="head1">
          <img src="@/assets/img/jianpan/秒表.png" alt="" />
          <span>倒计时：</span>
          <span>{{ timeDao }}</span>
        </div>
        <div class="head1">
          <img src="@/assets/img/jianpan/速度.png" alt="" />
          <span>打字速度：</span>
          <span>{{ kpm }} KPM </span>
        </div>
        <div class="head1">
          <img src="@/assets/img/jianpan/正确.png" alt="" />
          <span>正确：</span>
          <span>{{ trueNum }}字</span>
        </div>
        <div class="head1">
          <img src="@/assets/img/jianpan/错误.png" alt="" />
          <span>错误：</span>
          <span>{{ falseNum }}字</span>
        </div>
      </div>
      <div class="ctx-main">
        <div class="cur-item">
          <span id="cur-item-width">
            <span
              v-for="(item, index) in curList"
              :key="index + 'word'"
              class="hello-item"
              :class="{ active: index < Idx, wrong: !item.isTrue }"
            >
              <span :class="[item.val === ' ' ? 'kong' : '']">{{
                item.val
              }}</span>
            </span>
          </span>
          <!-- {{curList}} -->
        </div>
        <div class="inps">
          <input
            ref="inp"
            id="inp"
            :style="`width:${spanWidth}px`"
            @keyup="keydown($event)"
            autofocus="autofocus"
            @focus="handleFocus"
            @click="handleFocus"
            autocomplete="off"
            @input="kd($event)"
            v-model="val"
          />
        </div>
        <div class="item-fu">
          <div class="item" v-for="(item, index) in allListCopy" :key="index">
            {{ item }}
          </div>
        </div>
      </div>
    </div>
    <div class="djs" v-if="isShowDaojishi">{{ djs }}</div>
  </div>
</template>
<script>
// import HeadComp from '../head/head'
import Header from "@/components/Header";
import { startTyping, finishTyping } from "@/api/jianpan";

export default {
  data() {
    return {
      timeDao: "2分00秒",
      kpm: 0,
      trueNum: 0,
      falseNum: 0,
      isFrist: 1, //是否是第一次点击，时间初始
      val: "", //input框值
      preVal: "", //上一个input框值
      count: 0, //累积
      Idx: 0, //指针
      curCount: 0, //kpm 个数
      curTime: 0, //kpa 时间
      curItem: "",
      allIdx: 0, //总指针
      curList: [],
      allList: [],
      allListCopy: [],
      res: [],
      allRes: [],
      time: null,
      startTime: "",
      entTime: "",
      djs: 3, //倒计时用
      tm: null, //定时器
      isShowDaojishi: true, //倒计时遮罩
      spanWidth: 600,
      baseLine:0,
      inputLine:0,
    };
  },
  created() {
    this.init();
  },
  mounted() {
    this.time = Date.now(); //开始时间 初次进来的话
  },
  methods: {
    getSpanWidth() {
      let width = document.getElementById("cur-item-width").offsetWidth;
      this.spanWidth = width + 40;
    },
    t() {
      return `${new Date().getFullYear()}-${
        new Date().getMonth() + 1
      }-${new Date().getDate()} ${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()}`;
    },
    clearCodeAll() {
      let saveList = this.res;
      let val = this.val ? this.val.length : 0;
      saveList.map((item, index) => {
        if (index + 1 > val) {
          if (item.status) {
            this.trueNum--;
          } else {
            this.falseNum--;
          }
          this.curList[index].isTrue = true;
        }
      });

      saveList.splice(this.val.length);
      this.$forceUpdate();
    },
    handleFocus() {
      document.getElementById("inp").selectionStart = this.val.length;
      document.getElementById("inp").selectionEnd = this.val.length;
    },
    keydown(p) {
      // 回溯 backspace
      if (
        p.keyCode == 37 ||
        p.keyCode == 38 ||
        p.keyCode == 39 ||
        p.keyCode == 40
      ) {
        this.handleFocus();
        return false;
      }
      if (p.key === "Backspace" && this.res.length) {
        this.clearCodeAll();
        this.Idx = this.res.length;
        // console.log('1')
        // let pop = this.res.pop();
        // if (pop.status) {
        //   this.trueNum--;
        // } else {
        //   this.falseNum--;
        // }
        // 错误字标红撤销
        // this.curList.splice(this.Idx, 1, {
        //   isTrue: true,
        //   val: this.curList[this.Idx].val,
        // });

        // 中文字符数不对等，所以input为删除到空值时，直接初始化该项
        if (this.val.length === 0) {
          this.Idx = 0;
          this.res = [];
          this.curList = [];
          this.trueNum = 0;
          this.falseNum = 0;
          this.allList[this.allIdx].split("").forEach((e) => {
            this.curList.push({
              val: e,
              isTrue: true,
            });
          });
        }
      }
      // 中文输入法回车 回溯一次
      if (
        (p.code === "Enter" || p.code === "Space") &&
        p.keyCode !== 13 &&
        p.keyCode !== 32
      ) {
        this.Idx--;
        let popE = this.res.pop();
        if (popE.status) {
          this.trueNum--;
        } else {
          this.falseNum--;
        }
        // 错误字标红
        this.curList.splice(this.Idx, 1, {
          isTrue: true,
          val: this.curList[this.Idx].val,
        });
      }
    },
    kd(p) {
      //  || p.data.length !== 1
      if (p.data === null || p.data === undefined) return;

      if (this.Idx < this.curList.length) {
        if (p.data.slice(-1) === this.curList[this.Idx].val) {
          this.res.push({
            time: Date.now() - this.time,
            status: true,
            key: this.curList[this.Idx].val,
          });
          this.trueNum++;
        } else {
          this.res.push({
            time: Date.now() - this.time,
            status: false,
            key: this.curList[this.Idx].val,
          });
          // 错误字标红
          this.curList.splice(this.Idx, 1, {
            isTrue: false,
            val: this.curList[this.Idx].val,
          });
          this.falseNum++;
        }
      }
      this.Idx++;
      this.time = Date.now();
      // kpm计算 当前输入字符数
      this.computeKPM()
      
      

      // 一句结束
      if (this.Idx >= this.curList.length) {
        this.$refs.inp.blur();
        this.allRes.push(this.res);
        this.curList = []; //清空
        this.val = "";
        this.res = [];
        this.Idx = 0;

        this.allIdx++;
        if (this.allIdx < this.allList.length) {
          let b = this.allListCopy.shift();
          b.split("").forEach((e) => {
            this.curList.push({
              val: e,
              isTrue: true,
            });
          });
          this.$nextTick(() => {
            this.getSpanWidth();
          });
        }
        this.$refs.inp.focus();
      }
      
      // 全结束
      if (this.allIdx === this.allList.length) {
        console.log(this.allIdx, this.allList.length, "全结束");
        document.querySelector("#inp").blur();
        this.endTime = this.t(); //结束时间
        // console.log(this.allRes,this.allRes[5],22222)
        let wordNum = 0; //总字符数
        let alltime = 0; //总的反应时间
        let right_count = 0; //总正确
        let wrong_count = 0; //总错误

        let list = {}; //储存结果
        let Regx = /^[A-Za-z]*$/;
        let aZ = [
          "a",
          "b",
          "c",
          "d",
          "e",
          "f",
          "g",
          "h",
          "i",
          "j",
          "k",
          "l",
          "m",
          "n",
          "o",
          "p",
          "q",
          "r",
          "s",
          "t",
          "u",
          "v",
          "w",
          "x",
          "y",
          "z",
        ];
        let Za = [
          "A",
          "B",
          "C",
          "D",
          "E",
          "F",
          "G",
          "H",
          "I",
          "J",
          "K",
          "L",
          "M",
          "N",
          "O",
          "P",
          "Q",
          "R",
          "S",
          "T",
          "U",
          "V",
          "W",
          "X",
          "Y",
          "Z",
        ];

        this.allRes.forEach((e) => {
          wordNum += e.length;
          // 每一句
          e.forEach((e) => {
            alltime += e.time; //总时间
            e.status ? right_count++ : wrong_count++; //正确错误次数
            if (Object.prototype.hasOwnProperty.call(list, e.key)) {
              list[e.key] = {
                time: list[e.key].time + e.time, //这个字母的总时间
                trueCount: e.status
                  ? list[e.key].trueCount + 1
                  : list[e.key].trueCount,
                count: list[e.key].count + 1,
              };
            } else {
              list[e.key] = {
                time: e.time,
                trueCount: e.status ? 1 : 0,
                count: 1,
              };
            }
          });
        });

        // 结果处理成数组 排序
        let a = Object.entries(list); //list列表
        let d = []; //数组a的copy  去除其中不是字母的项
        for (let i = 0; i < a.length; i++) {
          if (!Regx.test(a[i][0])) {
            continue;
          }
          d.push(a[i]);
        }
        let z = []; //按照字母顺序排列
        d.forEach((item) => {
          console.log(aZ.indexOf(item[0]));
          z[aZ.indexOf(item[0])] = {
            key: Za[aZ.indexOf(item[0])],
            value: item[1],
          };
        });

        // 结束传值给 4页
        let data = {
          startTime: this.startTime,
          endTime: this.endTime,
          wordNum: wordNum,
          value: z,
          kpm:this.kpm
        };

        // 发送给后台
        let response_time_list = [];
        let wrong_letter_list = [];
        z.forEach((e) => {
          response_time_list.push({
            [e.key]: Math.round((e.value.time / e.value.count) * 1000) / 1000,
          });
          wrong_letter_list.push({
            [e.key]: e.value.count - e.value.trueCount,
          });
        });
        let sendData = {
          test_time:
            (new Date(this.endTime).getTime() -
              new Date(this.startTime).getTime()) /
            1000,
          kpm: Math.floor(this.kpm),
          start_time: this.startTime,
          average_response_time: alltime,
          right_count: right_count,
          wrong_count: wrong_count,
          article_list: this.allList,
          response_time_list: response_time_list,
          wrong_letter_list: wrong_letter_list,
        };
        finishTyping(sendData).then((res) => {
          console.log("发送数据完毕", res);
        });

        this.$router.push({
          path: "/functionCenter/keyboard/page4",
          query: data,
        });
        return;
      }
    },
    computeKPM(){
      if(this.allIdx != this.inputLine){
         this.baseLine = this.curCount
         this.inputLine++
      }
      this.curCount = this.baseLine + this.res.length
    },
    // 时间到了
    sendInfo() {
      this.allRes.push(this.res);
      this.endTime = this.t(); //结束时间

      console.log(this.startTime, this.endTime, "this.startTime = this.t()");

      let wordNum = 0; //总字符数
      let alltime = 0; //总的反应时间
      let right_count = 0; //总正确
      let wrong_count = 0; //总错误

      let list = {}; //储存结果
      let Regx = /^[A-Za-z]*$/;
      let aZ = [
        "a",
        "b",
        "c",
        "d",
        "e",
        "f",
        "g",
        "h",
        "i",
        "j",
        "k",
        "l",
        "m",
        "n",
        "o",
        "p",
        "q",
        "r",
        "s",
        "t",
        "u",
        "v",
        "w",
        "x",
        "y",
        "z",
      ];
      let Za = [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ];

      this.allRes.forEach((e) => {
        wordNum += e.length;
        // 每一句
        e.forEach((e) => {
          alltime += e.time;
          e.status ? right_count++ : wrong_count++;
          if (Object.prototype.hasOwnProperty.call(list, e.key)) {
            list[e.key] = {
              time: list[e.key].time + e.time, //这个字母的总时间
              trueCount: e.status
                ? list[e.key].trueCount + 1
                : list[e.key].trueCount,
              count: list[e.key].count + 1,
            };
          } else {
            list[e.key] = {
              time: e.time,
              trueCount: e.status ? 1 : 0,
              count: 1,
            };
          }
        });
      });

      // 结果处理成数组 排序
      let a = Object.entries(list); //list列表
      let d = []; //数组a的copy  去除其中不是字母的项
      for (let i = 0; i < a.length; i++) {
        if (!Regx.test(a[i][0])) {
          continue;
        }
        d.push(a[i]);
      }
      let z = []; //按照字母顺序排列
      d.forEach((item) => {
        z[aZ.indexOf(item[0])] = {
          key: Za[aZ.indexOf(item[0])],
          value: item[1],
        };
      });

      // 结束传值给 4页
      let data = {
        startTime: this.startTime,
        endTime: this.endTime,
        wordNum: wordNum,
        value: z,
        kpm:this.kpm
      };

      // 发送给后台
      let response_time_list = [];
      let wrong_letter_list = [];
      z.forEach((e) => {
        response_time_list.push({
          [e.key]: Math.round((e.value.time / e.value.count) * 1000) / 1000,
        });
        wrong_letter_list.push({
          [e.key]: e.value.count - e.value.trueCount,
        });
      });
      let sendData = {
        test_time:
          (new Date(this.endTime).getTime() -
            new Date(this.startTime).getTime()) /
          1000,
        kpm: Math.floor(this.kpm),
        start_time: this.startTime,
        average_response_time: alltime,
        right_count: right_count,
        wrong_count: wrong_count,
        article_list: this.allList,
        response_time_list: response_time_list,
        wrong_letter_list: wrong_letter_list,
      };
      console.log("sendData", sendData);
      finishTyping(sendData).then((res) => {
        console.log("发送数据完毕", res);
      });

      this.$router.push({
        path: "/functionCenter/keyboard/page4",
        query: data,
      });
    },
    init() {
      startTyping()
        .then((res) => {
          // this.startTime = res.startTime//开始时间 .slice(0,2)
          this.allList = [...res.data.article];
          this.allListCopy = [...res.data.article];
          let a = this.allListCopy.shift();
          console.log(this.allList, a);
          a.split("").forEach((e) => {
            this.curList.push({
              val: e,
              isTrue: true,
            });
          });

          this.tm = setInterval(this.daojishi, 1000);
          this.$nextTick(() => {
            this.getSpanWidth();
          });
        })
        .catch((err) => {
          console.log(err, "err");
        });
    },
    daojishi() {
      this.djs--;
      if (this.djs <= 0) {
        clearInterval(this.tm);
        this.isShowDaojishi = false;
        this.timeL(120); //倒计时定时器 秒
        this.startTime = this.t(); //初始化开始时间
        this.time = Date.now(); //开始时间 初次进来的话
        document.querySelector("#inp").focus();
      }
    },
    timeL(p) {
      let maxtime = p;
      let timer;
      let _this = this;
      function CountDown() {
        _this.curTime =
          (Date.now() - new Date(_this.startTime).getTime()) / 1000 / 60;
          console.log(_this.curCount,_this.curTime)
        _this.kpm = (Math.floor(_this.curCount / _this.curTime*100)/100).toFixed(2);
        if (maxtime > 0) {
          let minutes = Math.floor(maxtime / 60),
            seconds = Math.floor(maxtime % 60);
          _this.timeDao = minutes + "分" + seconds + "秒";
         
         if(_this.$route.path.indexOf("page3") == -1){
           
          clearInterval(timer)
        }
          --maxtime;
        } else {
          clearInterval(timer);
          _this.sendInfo(); //时间到发送值  ==》结束
        }
      }
      timer = setInterval(() => {
        CountDown();
      }, 1000);
    },
    goStudyCenter() {
      this.$router.push({
        name: "keyboard1",
      });
    },
  },
  components: { Header },
};
</script>
<style lang="stylus" scoped>
@import './page3.styl';
</style>